package no.ntnu.fp.handlers;

import java.io.IOException;
import java.util.List;

import no.ntnu.fp.connection.ReceiveWorker;
import no.ntnu.fp.handler.Handler;
import no.ntnu.fp.handlers.exceptions.InvalidUserCredentialsException;
import no.ntnu.fp.messages.Message;
import no.ntnu.fp.messages.impl.AlreadyLoggedInMessage;
import no.ntnu.fp.messages.impl.LoginFailedMessage;
import no.ntnu.fp.messages.impl.LoginMessage;
import no.ntnu.fp.messages.impl.LoginSuccessfulMessage;
import no.ntnu.fp.model.Appointment;
import no.ntnu.fp.model.Employee;
import no.ntnu.fp.model.Meeting;
import no.ntnu.fp.model.Notice;
import no.ntnu.fp.net.co.Connection;
import no.ntnu.fp.server.MainConnection;
import no.ntnu.fp.services.AppointmentService;
import no.ntnu.fp.services.EmployeeService;
import no.ntnu.fp.services.MeetingService;
import no.ntnu.fp.services.NoticeService;

public class LoginHandler implements Handler {

	private final EmployeeService employeeService;
	private final NoticeService noticeService;
	private final MeetingService meetingService;
	private final AppointmentService appointmentService;
	
	public LoginHandler(EmployeeService employeeService,
			NoticeService noticeService, MeetingService meetingService,
			AppointmentService appointmentService) {
		this.employeeService = employeeService;
		this.noticeService = noticeService;
		this.meetingService = meetingService;
		this.appointmentService = appointmentService;
	}



	@Override
	public void handleMessage(Message message) {
		LoginMessage loginMessage = (LoginMessage)message;
		Connection connection = ReceiveWorker.getThreadLocalConnection();
		Employee employee = null;
		Message reply = null;
		try {
			employee = employeeService.getEmployeeByCredentials(
					loginMessage.getUsername(), loginMessage.getPassword());
			if (MainConnection.getConnection(employee) != null) {
				reply = new AlreadyLoggedInMessage();
			} else {
				MainConnection.registerEmployee(employee, connection);
				List<Appointment> appointments = appointmentService.getApppointmentsByEmployee(employee);
				List<Meeting> meetings = meetingService.getMeetingsByEmployee(employee);
				List<Notice> notices = noticeService.getUnreadNoticesByEmployee(employee);
	
				reply = new LoginSuccessfulMessage(employee, appointments, meetings, notices);
			}			
		} catch (InvalidUserCredentialsException ex) {
			reply = new LoginFailedMessage();
		}
		try {
			connection.send(reply.toString());
		} catch (IOException e) {
			System.err.println(e);
			try {
				connection.close();
			} catch (IOException ex) { }
			MainConnection.unregisterEmployee(employee);
		}
	}
}
